package cn.com.project;

import io.seata.spring.annotation.GlobalTransactional;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@SpringBootApplication
@EnableDiscoveryClient
@EnableDubbo
@RestController
@RefreshScope
public class DubboConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(DubboConsumerApplication.class, args);
    }

    /**
     * Nacos Config
     */
    @Value("${userConfig.name:Wang}")
    private String name;

    @Value("${userConfig.age:15}")
    private Integer age;

    @GetMapping("/user")
    public String user() {
        System.out.println("Consumer Call : sayHello");
        return apiService.sayHello("Hello Nacos Config! Hello " + name + " " + age + "!");
    }

    /**
     * Dubbo
     */
    @DubboReference(version = "1.0.0", protocol = "dubbo")
    private ApiService apiService;

    @GetMapping("/sayHello")
    public String sayHello(String name) {
        System.out.println("Consumer Call : sayHello");
        return apiService.sayHello(name);
    }

    @GetMapping("/saveUser")
    public User saveUser() {
        System.out.println("Consumer Call : saveUser");
        User user = new User(name, age);
        apiService.saveUser(user);
        return user;
    }

    @GetMapping("/listUser")
    public List<User> listUser() {
        System.out.println("Consumer Call : listUser");
        return apiService.listUser();
    }

    /**
     * Seata
     */
    @GetMapping("/order")
    @GlobalTransactional
    public String order() {
        String result = apiService.account("U1", 10);
        System.out.println("account----------" + result);
        if (!"SUCCESS".equals(result)) {
            throw new RuntimeException();
        }

        result = apiService.storage("G1", 1);
        System.out.println("storage----------" + result);
        if (!"SUCCESS".equals(result)) {
            throw new RuntimeException();
        }
        return "SUCCESS";
    }

}
